﻿using System;
using System.Collections.Generic;
using System.Text;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.ZLog;

namespace UtilZ.Dotnet.Ex.Communication.Net.Telnet.Commands
{
    /// <summary>
    /// 设置编码命令
    /// </summary>
    [TelnetCommandAttribute(TelnetCommandConstant.ENCODING)]
    internal class SettingEncodingCommand : TelnetCommandAbs
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public SettingEncodingCommand()
            : base()
        {

        }




        /// <summary>
        /// 执行命令[执行成功返回true;否则返回false]
        /// </summary>
        /// <param name="telnetClient">执行命令的连接</param>
        /// <param name="paraArr">命令参数</param>
        /// <returns>执行结果</returns>
        protected override bool PrimitiveExcute(IListenTelnetClient telnetClient, string[] paraArr)
        {
            if (paraArr.Length < 3)
            {
                return false;
            }

            string result;
            StringBuilder sb;
            try
            {
                Encoding encoding = EncodingEx.GetEncoding(paraArr[2]);
                if (encoding != null)
                {
                    telnetClient.MessageEncoding = encoding;
                    result = $"{TelnetConstant.END_LINE_CURSOR}set {paraArr[2]} succes{TelnetConstant.END_LINE_CURSOR}";
                    telnetClient.SendMessage(result);
                    return true;
                }

                sb = new StringBuilder();
            }
            catch (Exception ex)
            {
                sb = new StringBuilder();
                sb.AppendLine(ex.Message);
                ZLoger.Warn(ex);
            }

            foreach (var encodingInfo in Encoding.GetEncodings())
            {
                if (sb.Length > 0)
                {
                    sb.Append('|');
                }
                sb.Append(encodingInfo.Name);
            }

            result = $"{TelnetConstant.CURSOR}encoding invalid,support encodings \"{sb.ToString()}\"{TelnetConstant.END_LINE_CURSOR}";
            telnetClient.SendMessage(result);
            return true;
        }
    }
}
